package com.example.zzx.dovebook.booktrace

import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.amap.api.maps2d.AMapUtils
import com.amap.api.maps2d.model.LatLng
import com.example.baselibrary.commonutil.FormatUtil
import com.example.baselibrary.commonutil.ToastUtil
import com.example.baselibrary.widget.LoadingStateView
import com.example.library.BaseAdapter
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.ValueWrapper.TYPE_FAILED
import com.example.zzx.dovebook.booktrace.model.BookTrace
import com.example.zzx.dovebook.login.LoginCheck
import com.example.zzx.dovebook.user.UserManager
import kotlinx.android.synthetic.main.activity_book_trace.*

class BookTraceActivity: BaseActivity<BookTraceViewModel>() {

    /**
     * 图书正在漂流中
     */
    val STATUS_DRIFTING = 2
    /**
     * 已经有用户接收了这个图书
     */
    val STATUS_RECEIVED = 1
    /**
     * 漂流结束
     */
    val STATUS_CLOSED = 0

    lateinit var adapter: BaseAdapter
    lateinit var emptyView: LoadingStateView

    lateinit var bookId: String
    var bookState: Int = 0

    override fun getLayoutId(): Int {
        return R.layout.activity_book_trace
    }

    override fun getStatusBarColor(): Int = STATUS_BAR_TRANSPARENT

    override fun createViewModel(): Class<BookTraceViewModel> {
        return BookTraceViewModel::class.java
    }

    override fun createRepository(): Any {
        return BookTraceRepository()
    }

    override fun initViews(savedInstanceState: Bundle?) {
        setupTitleLayout()

        setupActionBar()

        setupRecyclerView()
    }

    private fun setupTitleLayout() {
        currentState.text = getBookStatusTip()
    }

    override fun initIntent(savedInstanceState: Bundle?) {
        bookId = intent.getStringExtra(getString(R.string.book_id_arg_name))
        bookState = intent.getIntExtra(getString(R.string.book_status_arg_name), STATUS_DRIFTING)
        if (bookId == null) {
            ToastUtil.shortToast(this, "出错了...")
            finish()
        }
    }

    override fun initOptions(savedInstanceState: Bundle?) {
        queryBookTrace()
    }

    private fun queryBookTrace() {
        viewModel.queryBookTrace(bookId, 0).observe(this, Observer {
            if (it?.value == null) {
                if (it?.type == TYPE_FAILED) {
                    emptyView.failed()
                } else {
                    emptyView.empty()
                }
                return@Observer
            }
            emptyView.success()
            adapter.cancelEmptyState()
            val bookTraceList = it?.value as List<BookTrace>
            adapter.add(bookTraceList)
            passCount.text = bookTraceList.size.toString() + "次"
            arrivalTime.text = FormatUtil.dateFormat(bookTraceList[bookTraceList.size - 1].createAt)
            updateDistance(bookTraceList)
        })
    }

    private fun setupActionBar() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    private fun setupRecyclerView() {
        emptyView = LoadingStateView(this)
        emptyView.setTextColor(ContextCompat.getColor(this, R.color.text_color_secondary))
        emptyView.setOnRetryListener {
            emptyView.loading()
            queryBookTrace()
        }
        adapter = BaseAdapter.Builder().emptyView(emptyView).build()
        adapter.emptyState()
        recyclerView.adapter = adapter
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun getBookStatusTip(): String {
        return when (bookState) {
            STATUS_DRIFTING -> "漂流中"
            STATUS_RECEIVED -> "已捞起"
            else -> "已退出"
        }
    }

    @LoginCheck
    fun requestReceive(bookId: String, bookShareId: String, uploadUserId: String) {
        val requestUserId = UserManager.getInstance(this).loginUserId ?: ""
        if (TextUtils.equals(requestUserId, uploadUserId)) {
            ToastUtil.shortToast(this, "不能接收自己分享的书籍")
            return
        }
        viewModel.requestReceive(bookId, bookShareId, requestUserId, uploadUserId).observe(this, Observer {
            it?.let {
                ToastUtil.longToast(this, "申请成功，请等待答复")
            }
        })
    }

    private fun updateDistance(bookTraceList: List<BookTrace>) {
        val startPoint = findStartAvailablePoint(bookTraceList)
        val endPoint = findEndAvailablePoint(bookTraceList)
        startPoint?.apply {
            val distance = getDistance(startPoint, endPoint!!)
            passDistance.text = distance
        }
    }

    private fun findStartAvailablePoint(bookTraceList: List<BookTrace>): LatLng? {
        for (trace in bookTraceList) {
            if (isLocationAvailable(trace)) {
                return LatLng(trace.latitude, trace.longitude)
            }
        }
        return null
    }

    private fun findEndAvailablePoint(bookTraceList: List<BookTrace>): LatLng? {
        for (trace in bookTraceList.reversed()) {
            if (isLocationAvailable(trace)) {
                return LatLng(trace.latitude, trace.longitude)
            }
        }
        return null
    }

    private fun getDistance(startPoint: LatLng, endPoint: LatLng): String {
        val distance = AMapUtils.calculateLineDistance(startPoint, endPoint)
        return FormatUtil.distanceFormat(distance)
    }

    private fun isLocationAvailable(trace: BookTrace): Boolean {
        return !(trace.latitude == 0.0 && trace.longitude == 0.0)
    }
}